package com.dounine.clouddisk360.parser;

import java.io.IOException;
import java.net.URISyntaxException;

import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dounine.clouddisk360.parser.deserializer.user.token.UserToken;
import com.dounine.clouddisk360.parser.deserializer.user.token.UserTokenConfig;
import com.dounine.clouddisk360.parser.deserializer.user.token.UserTokenConst;
import com.dounine.clouddisk360.parser.deserializer.user.token.UserTokenRequestInterceptor;
import com.dounine.clouddisk360.parser.deserializer.user.token.UserTokenResponseHandle;
import com.dounine.clouddisk360.pool.PoolingHttpClientConnection;

public class UserTokenParser extends BaseParser<UserTokenConfig> {

	private static final Logger LOGGER = LoggerFactory.getLogger(UserTokenParser.class);
	
	public static final String GET_TOKEN_URL = "https://login.360.cn/";

	@Override
	public void initConfig(UserTokenConfig userTokenConfig) {
		super.initConfig(userTokenConfig);//必需调用父类的initConfig方法,或者重写里面所定义的cookieStore路径
	}

	public UserToken parse(String userName) {
		HttpGet request = initRequest(userName,super.config);;
		return execute(request);
	}

	public HttpGet initRequest(String userName, UserTokenConfig config) {
		try {
			URIBuilder uri = new URIBuilder(GET_TOKEN_URL);
			uri.addParameter(UserTokenConst.SRC_KEY, UserTokenConst.SRC_VAL);
			uri.addParameter(UserTokenConst.FROM_KEY, UserTokenConst.FROM_VAL);
			uri.addParameter(UserTokenConst.CHARSET_KEY, UserTokenConst.CHARSET_VAL);
			uri.addParameter(UserTokenConst.REQUESTSCEMA_KEY, UserTokenConst.REQUESTSCEMA_VAL);
			uri.addParameter(UserTokenConst.O_KEY, UserTokenConst.O_VAL);
			uri.addParameter(UserTokenConst.M_KEY, UserTokenConst.M_VAL);
			uri.addParameter(UserTokenConst.USERNAME_NAME, userName);
			HttpGet request = new HttpGet(uri.build());
			return request;
		} catch (URISyntaxException e) {
			LOGGER.error("生成用户登录token令牌请求对象失败");
		}
		return null;
	}
	
	public UserToken execute(HttpGet request) {
		
		super.httpClient = HttpClients.custom()
				.setConnectionManager(PoolingHttpClientConnection.getInstalce())
				.addInterceptorLast(new UserTokenRequestInterceptor())
				.setDefaultRequestConfig(cookieRequestConfig())
				.build();
		try {
			return super.httpClient.execute(request,new UserTokenResponseHandle(this), super.httpClientContext);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

}
